package AgentesConcurso;

import jade.content.lang.sl.SLCodec;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import java.util.ArrayList;
import java.util.List;

import Ontologias.OntologiaConcursoFornecedores;
import Ontologias.PredicadoConcurso;
import Ontologias.ResultadoProposta;



@SuppressWarnings("serial")
public class AgenteRenegociador extends jade.core.Agent {

	AgenteDecisor agDecisor;
	PredicadoConcurso pConc;

	public void setup() {

		try {
			// REGISTO DO AGENTE NAS PAGINAS AMARELAS
			DFAgentDescription dfd = new DFAgentDescription();
			dfd.setName( getAID() );
			ServiceDescription sd  = new ServiceDescription();
			sd.setType( "AgenteRenegociador" );
			sd.setName( getLocalName() );
			dfd.addServices(sd);
			DFService.register(this, dfd );  
		}
		catch (FIPAException fe) { 
			fe.printStackTrace(); 
		}

		getContentManager().registerLanguage(new SLCodec());
		getContentManager().registerOntology(OntologiaConcursoFornecedores.getInstance());

		Object[] args = getArguments();


		this.agDecisor = (AgenteDecisor)args[0];
		this.pConc = (PredicadoConcurso)args[1];


		envia_renegocios();



	}



	public void envia_renegocios() {

		List<String> l_forn_concorrentes = new ArrayList<String>(agDecisor.getpResult().getPropostas().size());
		for(ResultadoProposta prop : agDecisor.getpResult().getPropostas()) l_forn_concorrentes.add(prop.getNomeFornecedor());


		ACLMessage cfp = new ACLMessage(ACLMessage.CFP);


		DFAgentDescription dfd = new DFAgentDescription();
		ServiceDescription sd  = new ServiceDescription();
		sd.setType( "Fornecedor" );
		dfd.addServices(sd);

		DFAgentDescription[] result = {};
		try {
			result = DFService.search(this, dfd);

		} catch (FIPAException e) {
			e.printStackTrace();
		}


		for (DFAgentDescription df : result) {

			if (l_forn_concorrentes.contains(df.getName().getLocalName())) {
				cfp.addReceiver(df.getName());
			}
		}


		try {


			cfp.setContentObject(pConc);
			this.addBehaviour(new PrazoRenegoceio(this.agDecisor,pConc));

		} catch (Exception ce) {
			ce.printStackTrace();
		}

		send(cfp);

	}


}
